<template>
	<view class="cotainer">
		<view class="object">
			<view class="recharge-object">充值用户</view>

			<view class="recharge-people">
				<text>姓名</text>
				<text>{{userInfo.name}}</text>
			</view>
			<view class="divider"></view>
			<view class="recharge-people">
				<text>学/工号</text>
				<text>{{userInfo.account}}</text>
			</view>
		</view>
		<view class="project">
			<view>
				<view class="project-type">
					<text>金额选择</text>
				</view>
				<view class="divider"></view>
			</view>
			<view class="recharge-select">
				<view class="recharge-body">
					<view v-for="(item, index) in number" :key="index"
						:class="['recharge-number', item.selected ? 'selected' : '']" @click="selectPrice(item, index)">
						{{ item.price }}
					</view>
					<view class="recharge-number" v-if="showCustomAmountButton" @click="openCustomAmountModal">
						自定义
					</view>
				</view>
			</view>
			<view>
				<view class="divider"></view>
				<view class="recharge-money">
					<text>实充金额</text>
					<text>{{ select }}</text>
				</view>
				<view class="divider"></view>
				<view class="recharge-way">
					<text>充值方式</text>
					<text>微信</text>
				</view>
			</view>
		</view>
		<button class="btn" @click="confirmRecharge">确认充值</button>

		<!-- Custom Amount Modal -->
		<view v-if="showCustomAmountModal" class="modal">
			<view class="modal-content">
				<text>请输入自定义金额 (最高200):</text>
				<input ref="customAmountInput" type="number" v-model="customAmount" />
				<view class="button-group">
					<button @click="setCustomAmount">确定</button>
					<button class="cancel-btn" @click="closeCustomAmountModal">取消</button>
				</view>
			</view>
		</view>
	</view>
</template>


<script>
	import {
		ajax
	} from '../../utils/request.js';

	export default {
		data() {
			return {
				number: [{
						id: 0,
						price: 5,
						selected: false
					},
					{
						id: 1,
						price: 10,
						selected: false
					},
					{
						id: 2,
						price: 20,
						selected: false
					},
					{
						id: 3,
						price: 30,
						selected: false
					},
				],
				select: '',
				showCustomAmountModal: false,
				customAmount: '',
				showCustomAmountButton: true,
				userInfo: [],
				sign: '',
				deviceInfo: null, // 新增设备信息存储
				characteristicId: null // 新增特征值ID存储
			};
		},
		methods: {
			selectPrice(item, index) {
				this.number.forEach((el) => {
					el.selected = false;
				});
				this.number[index].selected = true;
				this.select = item.price;
			},
			openCustomAmountModal() {
				this.clearSelection();
				this.showCustomAmountModal = true;
				this.$nextTick(() => {
					const inputElement = this.$refs.customAmountInput;
					if (inputElement && inputElement.$el) {
						inputElement.$el.focus();
					} else if (inputElement) {
						inputElement.focus();
					}
				});
			},
			closeCustomAmountModal() {
				this.showCustomAmountModal = false;
				this.customAmount = '';
			},
			setCustomAmount() {
				const amount = parseFloat(this.customAmount);
				if (amount > 0 && amount <= 200) {
					this.select = amount;
					this.closeCustomAmountModal();
				} else {
					uni.showToast({
						title: '请输入有效的金额 (1-200)',
						icon: 'none',
					});
				}
			},
			confirmRecharge() {
				const selectedItem = this.number.find((item) => item.selected);
				const rechargeAmount = selectedItem ? (selectedItem.price === '自定义' ? this.select : selectedItem.price) :
					this.select;

				if (!rechargeAmount) {
					uni.showToast({
						title: '请选择充值金额',
						icon: 'none',
					});
					return;
				}

				const token = uni.getStorageSync('token');
				console.log(token);

				uni.login({
					provider: 'weixin',
					success: (res) => {
						if (res.code) {
							console.log('获取到的 code: ' + res.code);

							const userId = uni.getStorageSync('userId');

							ajax('/api/wxpay/coldwatermeterpaywx', 'POST', {
									code: res.code,
									total_fee: rechargeAmount,
									ss_mc: this.userInfo.ss_mc,
									userId: userId,
								})
								.then((data) => {
									console.log(data.msg);
									this.sign = data.msg.sign
									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: String(data.msg.TimeStamp),
										nonceStr: data.msg.nonce_str,
										package: "prepay_id=" + data.msg.responseObject.xml
											.prepay_id._cdata + "",
										signType: 'MD5',
										paySign: data.msg.sign,
										success: async (res) => {
											console.log('支付成功:', res);

											try {
												// 开启通知监听
												await this.enableNotifications();
												// 发送签名到设备
												await this.sendBluetoothCommand();

												uni.showLoading({
													title: '等待设备响应...'
												});

												// 设置超时检测
												setTimeout(() => {
													uni.hideLoading();
													uni.showToast({
														title: '设备响应超时',
														icon: 'none'
													});
												}, 30000);
											} catch (err) {
												console.error('蓝牙操作失败:', err);
												uni.showToast({
													title: err.message,
													icon: 'none'
												});
											}
										},
										fail: function(err) {
											console.log('fail:' + JSON.stringify(err));
										},
									});
								})
								.catch((error) => {
									console.error('请求失败:', error);
								});
						} else {
							console.log('登录失败！' + res.errMsg);
						}
					},
					fail: function(err) {
						console.log('调用登录接口失败', err);
					},
				});
			},
			clearSelection() {
				this.number.forEach((item) => {
					item.selected = false;
				});
				this.select = '';
			},
			getUserInfo() {
				this.userInfo = uni.getStorageSync('userInfo');
			},
			async enableNotifications() {
			  // 查找第一个支持notify的特征值
			  const service = this.deviceInfo.services.find(s => 
			    s.characteristics.some(c => c.properties.includes('notify'))
			  );
			  
			  if (!service) {
			    throw new Error('未找到支持通知的特征值');
			  }
			
			  const characteristic = service.characteristics.find(c => 
			    c.properties.includes('notify')
			  );
			
			  if (!characteristic) {
			    throw new Error('未找到支持通知的特征值');
			  }
			
			  return new Promise((resolve, reject) => {
			    uni.notifyBLECharacteristicValueChange({
			      deviceId: this.deviceInfo.deviceCode,
			      serviceId: service.serviceId,
			      characteristicId: characteristic.uuid,
			      state: true,
			      success: () => {
			        console.log('通知启用成功');
			        resolve();
			      },
			      fail: (err) => {
			        console.error('通知启用失败:', err);
			        reject(new Error('启用通知失败'));
			      }
			    });
			  });
			},
			// 初始化蓝牙适配器
			initBluetooth() {
				// 从本地存储获取设备信息
				this.deviceInfo = uni.getStorageSync('bluetoothDeviceInfo');
				if (!this.deviceInfo) {
					uni.showToast({
						title: '未找到设备信息，请返回重新连接',
						icon: 'none'
					});
					return;
				}
				console.log("设备id",this.deviceInfo.deviceCode,typeof(this.deviceInfo.deviceCode));

				// 监听特征值变化
				uni.onBLECharacteristicValueChange(res => {
					console.log('[蓝牙数据]', {
					    deviceId: res.deviceId,
					    serviceId: res.serviceId,
					    characteristicId: res.characteristicId,
					    value: Array.from(new Uint8Array(res.value))
					  });
					const hexArray = [];
					const view = new DataView(res.value);
					for (let i = 0; i < view.byteLength; i++) {
					  const byte = view.getUint8(i).toString(16).padStart(2, '0');
					  hexArray.push(byte);
					}
					const result=hexArray.join('').toUpperCase();
					console.log('接收数据:', result);
					// uni.showToast({ title: '收到响应数据', icon: 'none' });
					ajax("/api/meter/getcoldwaterrechargerecordBluetoothgetOn", 'POST', {
					  ss_mc:this.userInfo.ss_mc,
					  msg:result
					}).then(res => {
					  console.log("数据上传成功",res);
					}).catch(err=>{
						console.log("数据上传失败",err);
					});
					if (result) {
						uni.showToast({
							title: '充值成功',
							icon:'success'
						});
					} else {
						uni.showToast({
							title: '设备响应异常',
							icon: 'none'
						});
					}
				});
			},

			async sendBluetoothCommand() {
				let userId = uni.getStorageSync('userId');
			  let command = '';
			  // 获取发送信号
			  await ajax("/api/meter/getcoldwaterrechargerecordBluetoothOn", 'POST', {
			    userId: userId,
				xh:this.userInfo.account,
				name:this.userInfo.name
			  }).then(res => {
			    command = res.data.hex; 
			  });
			
			  console.log(" 发送信号...", command);
			  
			  if (!this.deviceInfo)  {
			    throw new Error('设备未连接');
			  }
			
			  // 查找所有支持写操作的特征值
			  const writeCharacteristics = this.deviceInfo.services 
			    .flatMap(service => service.characteristics) 
			    .filter(characteristic => characteristic.properties.includes('write')); 
			// && characteristic.properties.includes('write');
			  if (writeCharacteristics.length  === 0) {
			    throw new Error('未找到支持写操作的特征值');
			  }
			
			  // 转换为 ArrayBuffer
			  const buffer = this.encode(command); 
			  console.log(" 发送", buffer);
			
			  // 在所有支持写操作的特征值上执行写操作
			  for (const characteristic of writeCharacteristics) {
			    try {
			      await new Promise((resolve, reject) => {
			        uni.writeBLECharacteristicValue({ 
			          deviceId: this.deviceInfo.deviceCode, 
			          serviceId: characteristic.serviceId, 
			          characteristicId: characteristic.uuid, 
			          value: buffer,
			          success: () => {
			            console.log(` 指令成功发送到特征值 ${characteristic.uuid}`); 
			            resolve();
			          },
			          fail: (err) => {
			            console.error(` 指令发送失败到特征值 ${characteristic.uuid}:`,  err);
			            reject(new Error(`指令发送失败到特征值 ${characteristic.uuid}`)); 
			          }
			        });
			      });
			    } catch (err) {
			      console.error(err.message); 
			      // 继续尝试下一个特征值
			    }
			  }
			
			  console.log(' 所有支持写操作的特征值均已尝试发送指令');
			},
			// 正确代码（应填充数据）
			encode(hexString) {
			  const hex = hexString.replace(/\s/g, '');
			  if (hex.length % 2 !== 0) {
			    return Promise.reject(new Error('HEX数据长度不正确'));
			  }
			  
			  const buffer = new ArrayBuffer(hex.length / 2);
			  const dataView = new DataView(buffer);
			  for (let i = 0; i < hex.length; i += 2) {
			    const byte = parseInt(hex.substr(i, 2), 16);
			    dataView.setUint8(i/2, byte);
			  }
			  return buffer;
			}
		},
		onLoad(options) {
			this.getUserInfo();
			this.initBluetooth();
			// 设置监听
			this.setupNotificationListener();
		},
	};
</script>


<style scoped>
	body {
		margin: 0;
	}

	.cotainer {
		display: flex;
		flex-direction: column;
		height: 120vh;
		background: #f0e8e8;
	}

	.object {
		background: #fff;
		padding: 10px;
	}

	.object .recharge-object {
		border-left: 4px solid green;
		padding-left: 10px;
	}

	.object .recharge-people {
		margin: 10px;
		display: flex;
		justify-content: space-between;
	}

	.project {
		display: flex;
		flex-direction: column;
		background: #fff;
		padding: 0 10px;
		height: auto;
		justify-content: space-around;
	}

	.project .project-type {
		border-left: 4px solid green;
		padding-left: 10px;
	}

	.project .recharge-select {
		width: 100%;
		height: auto;
	}

	.project .recharge-select .recharge-body {
		display: flex;
		align-items: center;
		margin: 0 auto;
		width: 90%;
		flex-wrap: wrap;
	}

	.project .recharge-select .recharge-body .recharge-number {
		width: 29%;
		height: 50px;
		margin: 5px;
		border: 0.5px solid #e2e0e0;
		border-radius: 5px;
		display: flex;
		justify-content: center;
		align-items: center;
		cursor: pointer;
	}

	.selected {
		background-color: rgb(68, 207, 68);
		color: white;
	}

	.project .recharge-money {
		height: 50rpx;
		line-height: 50rpx;
		margin: 10rpx auto;
		display: flex;
		justify-content: space-between;
	}

	.project .recharge-way {
		height: 50rpx;
		line-height: 50rpx;
		margin: 10rpx auto;
		display: flex;
		justify-content: space-between;
	}

	.btn {
		display: flex;
		justify-content: center;
		margin: 10% auto;
		width: 70%;
		border-radius: 5px;
		align-items: center;
		height: 5%;
		background: rgb(68, 207, 68);
		color: #fff;
		box-sizing: border-box;
		cursor: pointer;
	}

	.divider {
		border: 0.5px solid #e2e0e0;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modal-content {
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
		width: 90%;
		/* 改为 90% 或其他适合的百分比 */
		max-width: 300px;
		text-align: center;
	}

	.modal-content input {
		width: 100%;
		padding: 10px;
		height: 40px;
		margin: 10px 0;
		border: 1px solid #ccc;
		border-radius: 5px;
		box-sizing: border-box;
		/* 确保 padding 和 border 不超出宽度 */
	}

	.button-group {
		display: flex;
		justify-content: space-between;
	}

	.button-group button {
		width: 48%;
		padding: 10px;
		border: none;
		border-radius: 5px;
		background-color: rgb(68, 207, 68);
		color: #fff;
		cursor: pointer;
	}

	.cancel-btn {
		background-color: #ccc;
	}
</style>